package com.xiongwei.protocol;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class HttpClient {

    public static String send(String hostname, Integer port, InvocationParam invocationParam) {

        try {
            URL url = new URL("http", hostname, port, "/");
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();

            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);

            OutputStream outputStream = httpURLConnection.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);
            oos.writeObject(invocationParam);
            oos.flush();
            oos.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            ObjectInputStream ois = new ObjectInputStream(inputStream);
            String result = (String)ois.readObject();

            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
